<template>
  <div class="app-container">
    <div v-show="!showDetails">
      <!-- 条件栏 -->
      <PageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      />
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :check-box="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
      >
        <template v-slot:col-name="scope">
          <span class="slip-edit" @click="openDetails(scope.row)">{{
            scope.row.name
          }}</span>
        </template>
      </TableContainer>
    </div>
    <Modify
      v-if="modifyVisible"
      :table-row="tableRow"
      :visible="modifyVisible"
      @callback="modifyCallback"
    />
    <PageDialog
      v-if="dialogInfo.visible"
      title="权限"
      width="800px"
      :bt-list="dialogInfo.btList"
      v-model:visible="dialogInfo.visible"
      @reset="close"
    >
      <el-tree
        ref="tree"
        :data="treeInfo.data"
        show-checkbox
        :props="treeInfo.defaultProps"
        :node-key="treeInfo.nodeKey"
        :default-checked-keys="treeInfo.checked"
        @check="getCurrentNode"
      ></el-tree>
    </PageDialog>
    <Details
      v-if="showDetails"
      v-model:visible="showDetails"
      :table-row="tableRow"
      @callback="callbackDetails"
    ></Details>
  </div>
</template>

<script setup name="sysPermissionTemplate">
import {
  getMenusDefaultChecked,
  getSysPermissionTemplate,
  batchUpdateSysPermissions,
  sysPermissionMenusTreeWithResources,
} from '@/api/base.js'
import Modify from './modify.vue'
import Details from './details'
const { proxy } = getCurrentInstance()

const tableRow = ref({})
const modifyVisible = ref(false)
// 过滤相关配置
const filterInfo = ref({
  query: {
    nameLike: '',
    sort: 'sort asc',
  },
  list: [
    {
      type: 'input',
      label: '模板名称',
      value: 'nameLike',
      list: 'originList',
      event: search,
    },
    {
      type: 'button',
      label: '搜索',
      btType: 'primary',
      event: search,
      show: true,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getSysPermissionTemplate,
  fieldList: [
    { label: '名称', value: 'name', type: 'slot' },
    { label: '编码', value: 'code' },
    { label: '类型', value: 'typeValue' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: true,
      },
      {
        label: '权限',
        event: showPermission,
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  visible: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: submitPermission,
      saveLoading: false,
      show: true,
    },
  ],
})

// 权限树
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
})
const selectOrg = ref({})
const showDetails = ref(false)
function getCurrentNode(data, data1) {
  //如果是底部节点,寻找父节点,并将父节点的子节点查看按钮设置上
  if (data.children === undefined && data1.halfCheckedNodes != null) {
    data1.halfCheckedNodes.forEach((val) => {
      if (
        val.id === data.parentId &&
        proxy.$refs.tree.getNode(val).indeterminate
      ) {
        val.children.forEach((item) => {
          if (item.code.endsWith(':list')) {
            proxy.$refs.tree.setChecked(item, true, false)
          }
        })
      }
    })
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
//查询
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function close() {
  dialogInfo.value.visible = false
}
function update(row) {
  tableRow.value = { ...row }
  modifyVisible.value = true
}
async function modifyCallback(reload) {
  modifyVisible.value = false
  if (reload) {
    tableInfo.value.refresh = Math.random()
  }
}
function showPermission(row) {
  selectOrg.value = row
  const params = {
    subjectId: selectOrg.value.id,
    subjectType: 'sys',
    resourceType: 'uri',
  }
  getMenusDefaultChecked(params).then((res) => {
    if (res && res.success) {
      treeInfo.value.checked = res.data
      sysPermissionMenusTreeWithResources().then((res) => {
        if (res.success) {
          dialogInfo.value.visible = true
          treeInfo.value.data = res.data
        }
      })
    }
  })
}
async function submitPermission() {
  const authList = proxy.$refs.tree.getCheckedNodes(false, true)
  if (!authList || authList.length === 0) {
    proxy.$message({
      message: '控制台权限至少勾选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let itemIndex = authList.findIndex((item) => item.code === 'dashboard')
  if (itemIndex === -1) {
    proxy.$message({
      message: '控制台权限至少勾选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  const data = []
  authList.forEach((authNode) => {
    data.push({
      subjectId: selectOrg.value.id,
      subjectType: 'sys',
      resourceType: authNode.type,
      resourceId: authNode.id,
      level: 'own_and_allot',
    })
  })
  batchUpdateSysPermissions(data).then((res) => {
    if (res && res.success) {
      dialogInfo.value.visible = false
    }
  })
}
function openDetails(row) {
  tableRow.value = row
  showDetails.value = true
}
function callbackDetails(data) {
  if (data === 'edit') {
    showDetails.value = false
    modifyVisible.value = true
  }
}

getList()
</script>

<style scoped></style>
